<?php
// +----------------------------------------------------------------------
// | xiongrui [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.xiongrui.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: molong <molong@tensent.cn> <http://www.xiongrui.cn>
// +----------------------------------------------------------------------

namespace app\common\controller;
use app\common\model\WxUser;
use Com\JsSdk;
use Com\JsApiPay;
use Com\WechatAuth;
use app\common\model\Cart as CartModel;

class Fornt extends Base {

	public function _initialize() {
		parent::_initialize();
		//	session('user', null);
	  // print_r(session('user'));exit();


// 		if(!session('?user') || empty(session('user.openid')) ){
// 			$oauth = & load_wechat('Oauth');
// 			$WechatUser = & load_wechat('User');

// 			$code = request()->get('code');
// 			if(empty($code)){
// 				$oauthResult = $oauth->getOauthRedirect(request()->url(true), 'abc', 'snsapi_base');
// 				Header("Location: $oauthResult");
// 			}else{
// 				$tokeninfo = $oauth->getOauthAccessToken();
// 			}
// 			$userinfo = $WechatUser->getUserInfo($tokeninfo['openid']);

// 			if(empty($userinfo['nickname'])){
// 				$userinfo = $oauth->getOauthUserinfo($tokeninfo['access_token'], $tokeninfo['openid']);
// 			}

// 			if(empty($userinfo['openid'])){
// 				$oauthResult = $oauth->getOauthRedirect(request()->url(true), 'abc', 'snsapi_userinfo');
// 				Header("Location: $oauthResult");
// 			}

// 			$databaseinfo = WxUser::where('openid="'.$tokeninfo['openid'].'"')->find();
// 			//获取微信用户数据
// 			$userinfo['status'] = 1;
// 			$userinfo['last_login_time'] = time();
// 			$userinfo['subscribe'] = isset($userinfo['subscribe']) ? isset($userinfo['subscribe']) : 0;
// 			//log($userinfo);
// 			trace($userinfo,'error');
// 			if($databaseinfo){
// 			 	$databaseinfo->save($userinfo);
// 			}else{
// 				if(!empty($userinfo['openid'])){
// 					$databaseinfo = WxUser::create($userinfo);
// 				}
// 			}

// 			update_session($databaseinfo['id']);

// 		}else{

// 		}

// 		$userSession = session('user');
// 		define('USER_ID', $userSession['id']);

// 		//判断是否是黑名单
// 		if($userSession['is_blacklist'] ==1){
// 			update_session(USER_ID);
// 			exit();
// 		}


		if(empty(USER_ID)){
			echo "<script>location.href='".$_SERVER["HTTP_REFERER"]."';</script>";exit();
		}
// 		//24小时后执行一次
// 		$map                = array('action_id' => 1, 'user_id' => USER_ID);
// 		$map['create_time'] = array('gt', time()-24*3600);

// 		$exec_count         = db('ActionLog')->where($map)->count();

// 		if(!$exec_count){
// 			action_log('user_login', 'WxUser', USER_ID, USER_ID);
// 			update_session(USER_ID);
// 		}


		//初始化cookie
		if(!cookie('?pay')){
			cookie('pay', 1); //改为货到付款 2
			cookie('way', 1);
			$arayacakId = \app\common\model\DeliveryArayacak::order('id desc')->value('id');
			cookie('zt_address', $arayacakId);
		}

// 		//认证用户第一次登陆送2个五元优惠券
// 		//$userSession['subscribe'] == 1 && $userSession['first_gift'] ==0
// 		if($userSession['first_gift'] ==0){
// 			db('WxUser')->where('id', USER_ID)->setInc('balance', 2);
// 			$date=date('Y-m-d H:m:s',	strtotime('2038-01-01'));   //30天后过期
// 			//自动生成优惠券
// 			$couponData =[
// 				['coupon_id'=>1,'uid'=>USER_ID,'code'=>date('md').rand_number(4),'total'=>'50','price'=>'5','deadline'=>$date],
// 				['coupon_id'=>1,'uid'=>USER_ID,'code'=>date('md').rand_number(4),'total'=>'50','price'=>'5','deadline'=>$date],
// 				['coupon_id'=>1,'uid'=>USER_ID,'code'=>date('md').rand_number(4),'total'=>'100','price'=>'10','deadline'=>$date]
// 			];
// 			model('CouponList')->saveAll($couponData);
// 			model('WxUser')->where('id', USER_ID)->update(['first_gift' => '1']);
// 			//更新session
// 			update_session(USER_ID);
// 		}

		//判读是否为关闭网站
		if (\think\Config::get('web_site_close')) {
			header("Content-type:text/html;charset=utf-8");
			echo $this->fetch('common@default/public/close');exit();
		}
// 		//绑定返利
// 		if(input('?rebate_code')){
// 				$wxuser = model('WxUser')->where('id', USER_ID)->value('rebate_code');
// 				if(!$wxuser){
// 					model('WxUser')->where('id', USER_ID)->update(['rebate_code' => input('rebate_code')]);
// 				}
// 		}







		//是否关注
		$this->assign('subscribe', session('user.subscribe'));
		//设置SEO
		$this->setSeo();

		$this->setHoverNav();
	}

	public function _empty($name)
	{
			//把所有城市的操作解析到city方法
			return $this->error('未找到该页面');
	}


	//当前栏目导航
	protected function setHoverNav() {
		//dump($_SERVER['PHP_SELF']);
	}

	public function judge_addresstype($first_area, $type){
  	$shopindex = cookie('shopindex');
  	if($shopindex == 'index/index/stindex'){
  		if($first_area != 1 || $type == 1){
  		 $this->error('实体店水果只支持观山湖区配送！');
  		}
  	}elseif ($shopindex == 'index/index/networkindex') {
  		if($type == 1){
  			$this->error('网约水果只支持市区配送！');
  		}
  	}elseif ($shopindex == 'index/index/mailindex') {

  	}

  }





	//设置运费
	protected function setFreight($formUrl ,$ft=10, $km=10 , $unit=2.5, $place_id =1, $user_id = USER_ID, $add_id = '') {

    $addressMap = [
			'user_id'=>$user_id,
			'type'=> cookie('address_type') ? cookie('address_type') : 0,
			'defaults'=>1
		];

		if(!empty($add_id)){
			$addressMap= ['id'=>$add_id];
		}
		$address = db('AddressNew')->where($addressMap)->find();
		$url = 'http://apis.map.qq.com/ws/direction/v1/driving/?from='.$formUrl.'&to='.$address['latlng'].'&output=json&callback=cb&key=QQ6BZ-24HC6-ZAXSZ-MTZAU-5MU2J-HEFEH';


		$pinfo = file_get_contents($url);
		$pinfo = json_decode($pinfo, true);
		$distance = round($pinfo['result']['routes'][0]['distance']/1000, 2);
		$disparity = round($distance-$km);

		//运费规则
		if($disparity>0){
			$freight = $ft+$disparity*$unit;
		}else {
			$freight = $ft;
		}
		$return = db('AddressNew')->where('id', $address['id'])->update(['place_id' => $place_id, 'freight'=>$freight, 'disparity'=>$distance]);
		if($return){
			return true;
		}else{
			return false;
		}

 }

 //判断是否是会员
 protected  function isMemberAndDiscount($price){
	 $phone = db('WxUser')->where('id', USER_ID)->value('phone');
	 $isMember = 0;
	 if($phone){
		 //$price =$price*0.97;
		 $isMember = 1;
	 }
	 $this->assign('isMember', $isMember);
	 return $price;
 }
//判断是否只有活动商品【如果只有活动商品，取消运费补贴】
	protected function isEventsGoods($goods_feature){
		$eventsGoods = 0;
  	if(count($goods_feature) == 1 && $goods_feature[0] == 5){
			$eventsGoods = 1;
		}
		$this->assign('eventsGoods', $eventsGoods);
		return $eventsGoods;
	}
//判断默认地址与收货地址的距离，从而修改运费
	protected function judgeDefaultAdressSetFreight(){
		$addressMap = [
			'user_id'=>USER_ID,
			'type'=> cookie('address_type') ? cookie('address_type') : 0,
			'defaults'=>1
		];
		$address = db('AddressNew')->where($addressMap)->find();
		if($address){
			$adLatlng = explode(",",$address['latlng']);

			$place = db('place')->select();
			$distanceArr = [];
			foreach ($place as $key => $value) {
					$latlng = explode(",",$value['latlng']);
					 $distanceArr[$key] = getDistance($latlng[0],$latlng[1],$adLatlng[0],$adLatlng[1]);
			}
			$pos = array_search(min($distanceArr), $distanceArr); //找到最小距离
			$this->setFreight($place[$pos]['latlng'], $place[$pos]['freight'], $place[$pos]['km'], $place[$pos]['unit'], $place[$pos]['id']);
		}


	}

	protected function allAdresSetFreight(){
		$all = db('AddressNew')->where(['type'=>0, 'disparity'=>0])->limit(10)->select();
		$place = db('place')->select();
		foreach ($all as $key => $ad) {
			$adLatlng = explode(",",$ad['latlng']);

			$distanceArr = [];
			foreach ($place as $key => $value) {
					$latlng = explode(",",$value['latlng']);
					 $distanceArr[$key] = getDistance($latlng[0],$latlng[1],$adLatlng[0],$adLatlng[1]);
			}
			$pos = array_search(min($distanceArr), $distanceArr); //找到最小距离

			$this->setFreight($place[$pos]['latlng'], $place[$pos]['freight'], $place[$pos]['km'], $place[$pos]['unit'], $place[$pos]['id'], $ad['user_id'], $ad['id']);
		}

	}

	protected function getWxUserInfo($openid){

		$WechatUser = & load_wechat('User');
		$userinfo = $WechatUser->getUserInfo($openid);
		if($userinfo){
			$databaseinfo = WxUser::where('openid="'.$userinfo['openid'].'"')->find();
			$databaseinfo->save($userinfo);
			update_session(USER_ID);
			return $databaseinfo;
		}else{
			return fasle;
		}

	}

	/**
	 * 初始化企业公共信息
	 */
	protected function setQiyeCommon(){
		$cid = input('cid');
		if(!$cid){
			echo '该店铺不存在';exit();
		}
		//企业信息
		$companyInfo = model('company')->find($cid);

		if(!$companyInfo){
			echo '该店铺不存在';exit();
		}
		//获取模型信息
		$mid = $companyInfo['goodsmodel_id'];
		cookie('goodsmodel_id', $mid);
		$modelInfo = model('goodsmodel')->find($mid);


		//清除购物车
		$this->destroyCartbyModelid($mid);

		//购物车信息
		$cinfo = CartModel::getNumAndPrice(['user_id'=>USER_ID]);

		//获取默认用户信息
		$userMap = ['uid'=>USER_ID, 'company_id'=>$cid, 'defaults'=>1];
		$qiyeUserInfo = model('Qiyeuser')->where($userMap)->find();

		$info['companyInfo'] = $companyInfo;
		$info['modelInfo'] = $modelInfo;
		$info['cinfo'] = $cinfo;
		$info['qiyeUserInfo'] = $qiyeUserInfo;
		cookie('company_id', $cid);
		cookie('init_price', $companyInfo['init_price']);
		$this->assign('cid', $cid);
		$this->assign('is_wxpay', $companyInfo['is_wxpay']);
		$this->assign('is_showprice', $companyInfo['is_showprice']);
		$this->assign('is_contact', $companyInfo['is_contact']);
		$this->assign('contact_dec', $companyInfo['contact_dec']);
		$this->assign('is_member', $companyInfo['is_member']);
		if($companyInfo['contact_qc']){
			$cqc = get_cover($companyInfo['contact_qc'], 'path');
		}else{
			$cqc = '/public/xsd/xsdwx.jpg';
		}

		$this->assign('contact_qc', $cqc);
		return $info;
	}

	protected function initModel($model_id, $place_id = 1){
		//设置店铺位置，及时配送，只有一个商品位置
		cookie('place_id', $place_id);
		//设置模块  1 = 及时配送
		cookie('goodsmodel_id', $model_id);
		cookie('init_price', config('initialdeliveryprice'));
		//删除不是该模块的购物车
		$this->destroyCartbyModelid(cookie('goodsmodel_id'));
	}



	/**
	 * 通过模块id删除购物车
	 * @param  [type] $model_id [description]
	 * @return [type]           [description]
	 */
	protected function destroyCartbyModelid($model_id){
		$map['user_id'] = USER_ID;
		$map['goodsmodel_id'] = ['neq', $model_id];
		$result = CartModel::destroy($map);
		if($result){
			cookie('deliverytime', null);
		}
	}


	protected function wechatJs(){
		$script = &  load_wechat('Script');
		$url = $this->request->url(true);
		$options = $script->getJsSign($url);
		$this->assign('wxoptions', $options);
	}



}
